//
//  LoginViewController.swift
//  App_Login
//
//  Created by 蒋晨成 on 2021/12/30.
//

import App_Common
import Center
import Chain
import Foundation
import RxCocoa
import RxSwift
import Service
import SnapKit
import Toast
import UICore
import UIKit

class LoginViewController: ViewController {
    private lazy var contentView = LoginView()
    private lazy var viewModel = LoginViewModel()
    private lazy var disposeBag = DisposeBag()
}

// MARK: - Override

extension LoginViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setup()
        bind()
    }
}

extension LoginViewController {
    func setupNav() {
        if (navigationController?.viewControllers.count ?? 0) > 1 {
            let backImage = LoginModular.image(named: "Common.Nav.Action.Back")
            addDefaultLeftBarButtonItem(image: backImage)
        }

        setNavigationBarTintColor(tintColor: LoginModular.color(name: "App.Dark1"))
    }

    func setup() {
        contentView.x.add(to: view).snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
    }
}

// MARK: - LoginViewDelegate

extension LoginViewController {
    func loginViewMobileSign(_: LoginView, mobile: String?) {
        guard let mobile = mobile else { return }
        Router.push(pattern: "login/verify/\(mobile)")
    }

    func loginViewAppleSignInClicked(_: LoginView) {
        handleAppleSignResponse()
    }

    func loginViewWeChatSignInClicked(_: LoginView) {
        DispatchQueue.main.async { [weak self] in
            self?.view.makeToastActivity(.center)
            UserCenter.Sign.WeChat.auth(
                code: "10086"
            ) { [weak self] result in
                self?.handleRPCResponse(result)
            }
            UserCenter.loginType = .wechat
        }
    }

    func handleAppleSignResponse() {
        DispatchQueue.main.async { [weak self] in
            self?.view.makeToastActivity(.center)
            UserCenter.Sign.Apple.auth(
                authorizationCode: "10086",
                identityToken: "10086",
                email: "10086",
                userIdentifier: "10086",
                fullName: "10086"
            ) { [weak self] result in
                self?.handleRPCResponse(result)
            }
            UserCenter.loginType = .apple
        }
    }

    func handleRPCResponse(_ response: Result<Void, Error>) {
        view.hideToastActivity()
        switch response {
        case .success:
            enterAppCallback?()
        case .failure(let error):
            view.makeToast(error.localizedDescription, position: .center)
        }
    }
}

private extension LoginViewController {
    func bind() {
        let input = LoginViewModel.Input(
            mobile: contentView.mobileTextField.rx.text.orEmpty.asDriver(),
            submitTap: contentView.sendButton.rx.tap.asObservable(),
            agree: contentView.protcolCheckBox.rx.tap.asObservable()
        )
        let output = viewModel.transform(input: input)

        output.agree
            .bind(to: contentView.protcolCheckBox.rx.isSelected)
            .disposed(by: disposeBag)

        output.submitState.drive(onNext: { [weak self] state in
            guard let self = self else { return }
            switch state {
            case .doing:
                self.view.makeToastActivity(.center)
            case .success:
                self.view.hideToastActivity()
                Router.push(pattern: "login/verify")
            case .failure(message: let message):
                self.view.hideToastActivity()
                self.view.makeToast(message, position: .center)
            }
        })
        .disposed(by: disposeBag)

        output.submitButtonValid
            .bind(to: contentView.sendButton.rx.isEnabled)
            .disposed(by: disposeBag)

        output.mobile
            .bind(to: contentView.mobileTextField.rx.text)
            .disposed(by: disposeBag)

        contentView.openUrl.subscribe(onNext: { url in
            Router.push(pattern: "WebBrowser/\(url.urlEncode())")
        })
        .disposed(by: disposeBag)
    }
}

extension LoginViewController: Routable {
    class func initialize(values _: [String: Any]) -> ViewController? {
        LoginViewController(nibName: nil, bundle: nil)
    }

    static let routePattern = "login"
}
